﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using DTO;
using System.Collections;

namespace BLL
{
    public class KhoiBLL
    {
        static int id = 0;
        QuanLyDiemDataContext DB = new QuanLyDiemDataContext();
        public IQueryable SelectDes()
        {
            return DB.Khois.OrderByDescending(s => s.MaKhoi).AsQueryable();
        }

        public string Insert(KhoiDTO khoidto)
        {
            try
            {
                Khoi khoi = new Khoi();
                khoi.MaKhoi = (id++).ToString();
                khoi.TenKhoi = khoidto.Tenkhoi;
                
                DB.Khois.InsertOnSubmit(khoi);
                DB.SubmitChanges();
                return "Thanh cong";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string Update(KhoiDTO khoidto)
        {
            try
            {
                Khoi khoi = DB.Khois.Where(s => s.MaKhoi == khoidto.Makhoi).FirstOrDefault();
            
                khoi.TenKhoi = khoidto.Tenkhoi;
                DB.SubmitChanges();
                return "Thanh cong";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public string Delete()
        {
            try
            {
                DB.SubmitChanges();
                return "Thanh cong";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string GetMaKhoi(string tenkhoi)
        {
            string k = DB.Khois.Where(s => s.TenKhoi == tenkhoi).Select(th => th.MaKhoi).FirstOrDefault().ToString();
            return k;
        }

        public string GetTenKhoi(string makhoi)
        {
            string k = DB.Khois.Where(s => s.MaKhoi == makhoi).Select(th => th.TenKhoi).FirstOrDefault().ToString();
            return k;
        }
        public List<KhoiDTO> getKhoi()
        {
            //lay het du lieu tu bang khoi
            List<Khoi> list = DB.Khois.ToList<Khoi>();
            //tao moi 1 doi tuong KhoiDTO de chua du lieu cua bang khoi
            List<KhoiDTO> listdto = new List<KhoiDTO>();
            foreach (Khoi khoi in list)
            {
                KhoiDTO k = new KhoiDTO();
                k.Makhoi = khoi.MaKhoi;
                k.Tenkhoi = khoi.TenKhoi;
                listdto.Add(k);
            }
            return listdto;
        }
        public bool check(string tenkhoi)
        {
            var kq = DB.Khois.Where(k=>k.TenKhoi==tenkhoi).ToList();
            int kt = 0;
            kt = kq.Count();
            if (kt == 0)
                return true;
            else return false;
        }
    }
}
